package com.wysiwyg.admin.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wysiwyg.admin.mapper.UserChangeMapper;
import com.wysiwyg.admin.model.dto.UserChangeDTO;
import com.wysiwyg.admin.model.po.AdminUserChangePO;
import com.wysiwyg.admin.service.mq.FlowMessageService;
import com.wysiwyg.flow.enums.FlowEventEnum;
import com.wysiwyg.flow.enums.FlowTag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;

import java.util.UUID;

/**
 * 用户变更服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserChangeService extends ServiceImpl<UserChangeMapper, AdminUserChangePO>
        implements IService<AdminUserChangePO> {

    private final FlowMessageService flowMessageService;

    /**
     * 启动用户变更流程
     */
    @Transactional(rollbackFor = Exception.class)
    public AdminUserChangePO startChangeFlow(UserChangeDTO dto) {
        // 1. 创建变更记录，初始状态为"待业务处理"(0)
        AdminUserChangePO changeRecord = buildChangeRecord(dto);
        changeRecord.setFlowStatus(0); // 待业务处理

        // 保存记录
        save(changeRecord);
        log.info("创建用户变更记录成功, changeNo={}, userId={}", changeRecord.getChangeNo(), changeRecord.getUserId());

        // 2. 发送异步消息，定义自定义回调处理
        String businessKey = "change-" + changeRecord.getId();

        SendCallback onSuccess = new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                // 消息发送成功：在新线程中更新数据库状态
                try {
                    AdminUserChangePO updateRecord = new AdminUserChangePO();
                    updateRecord.setId(changeRecord.getId());
                    updateRecord.setFlowStatus(1); // 业务处理中
                    updateRecord.setExecuteResult("消息发送成功: " + sendResult.getMsgId());

                    boolean updated = updateById(updateRecord);
                    if (updated) {
                        log.info("消息发送成功，更新变更状态: changeNo={}, msgId={}",
                                changeRecord.getChangeNo(), sendResult.getMsgId());
                    } else {
                        log.warn("消息发送成功但更新状态失败: changeNo={}", changeRecord.getChangeNo());
                    }
                } catch (Exception e) {
                    log.error("更新变更状态异常: changeNo={}", changeRecord.getChangeNo(), e);
                }
            }

            @Override
            public void onException(Throwable e) {
                // 这个方法在onSuccess回调中不需要实现
            }
        };

        SendCallback onFailure = new SendCallback() {
            @Override
            public void onException(Throwable e) {
                // 消息发送失败：在新线程中记录错误状态
                try {
                    AdminUserChangePO updateRecord = new AdminUserChangePO();
                    updateRecord.setId(changeRecord.getId());
                    updateRecord.setExecuteResult("消息发送失败: " + e.getMessage());
                    // 保持状态为0（待业务处理），让业务方决定是否重试

                    boolean updated = updateById(updateRecord);
                    if (updated) {
                        log.warn("消息发送失败，已记录错误状态: changeNo={}, error={}",
                                changeRecord.getChangeNo(), e.getMessage());
                    }
                } catch (Exception ex) {
                    log.error("记录发送失败状态异常: changeNo={}", changeRecord.getChangeNo(), ex);
                }
            }

            @Override
            public void onSuccess(SendResult sendResult) {
                // 这个方法在onFailure回调中不需要实现
            }
        };

        try {
            flowMessageService.sendAsyncMessage(FlowEventEnum.USER_CHANGE_STARTED,
                                              FlowTag.USER_CHANGE,
                                              businessKey,
                                              changeRecord,
                                              onSuccess,
                                              onFailure);
            log.info("异步消息发送请求已提交, businessKey={}", businessKey);
        } catch (Exception e) {
            log.error("提交异步消息发送请求失败, businessKey={}", businessKey, e);
            // 如果连发送请求都失败了，立即记录错误
            changeRecord.setExecuteResult("消息发送请求失败: " + e.getMessage());
            updateById(changeRecord);
        }

        return changeRecord;
    }

    /**
     * 构建变更记录
     */
    private AdminUserChangePO buildChangeRecord(UserChangeDTO dto) {
        AdminUserChangePO po = new AdminUserChangePO();

        // 生成变更单号
        po.setChangeNo("CHG" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase());

        // 基本信息
        po.setUserId(dto.getUserId());
        po.setUserName(dto.getUserName());
        po.setChangeType(dto.getChangeType());
        po.setChangeReason(dto.getChangeReason());
        po.setCreateBy(dto.getCreateBy());

        // 变更内容
        po.setOldWorkplace(dto.getOldWorkplace());
        po.setNewWorkplace(dto.getNewWorkplace());
        po.setOldJob(dto.getOldJob());
        po.setNewJob(dto.getNewJob());
        po.setOldTelephoneNumber(dto.getOldTelephoneNumber());
        po.setNewTelephoneNumber(dto.getNewTelephoneNumber());
        po.setOldMail(dto.getOldMail());
        po.setNewMail(dto.getNewMail());

        return po;
    }
}
